// pages/myself/merchant/BrandRenew.js
let network = null;
let utils = null;
let api = null;
const app = getApp();
var Zan = require('../../../dist/index');
let WxNotificationCenter = require('../../../utils/WxNotificationCenter.js');

Page(Object.assign({}, Zan.Tab, Zan.TopTips, {

  /**
   * 页面的初始数据
   */
  data: {
    selectedType: null,
    brandCost: null,
    selectedIndex: 0,
    brandId: null,
    type: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      brandId: options.brandId,
      type: options.type
    })

    // 品牌入驻所需的费用
    network._post_json(this, api.getBrandVip, {}, brandSuccess);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 选择支付方式
   */
  selectedPay: function (e) {
    this.setData({
      selectedIndex: e.currentTarget.dataset.index
    })
  },

  pay: function (e) {
    // 订单类型type  1=开通云商  2=开通来店  3=开通商圈  4=开通小游戏  5=提交工单
    network._post_json(this, api.pay1, { brandId: this.data.brandId, type: this.data.type, total: this.data.brandCost[this.data.selectedIndex].pv, totalKey: this.data.brandCost[this.data.selectedIndex].pk }, paySuccess);
  }
}))

// 品牌入驻所需的费用
var brandSuccess = function (that, res) {
  if (res.data.data) {
    let temp = [];
    for (let i = 0; i < res.data.data.length; i++) {
      if (that.data.type != 3) {
        if (res.data.data[i].pk == 'brandVipYear') {
          temp.push(res.data.data[i]);
        }
      } else {
        temp.push(res.data.data[i]);
      }
    }
    that.setData({
      brandCost: temp
    })
  }
}

// 创建订单
var paySuccess = function (that, res) {
  if (res.data.data) {
    let order = res.data.data;
    network._post_json(that, api.payPre1, { appId: app.globalData.appId, orderNo: order.orderNo, businessAppId: app.globalData.businessAppId, OrderDesc: order.orderDesc, totalFee: order.total }, payPreSuccess);
  }
}

// 生成预支付订单
var payPreSuccess = function (that, res) {
  if (res.data.data) {
    // 支付
    wx.requestPayment({
      timeStamp: res.data.data.timeStamp,
      nonceStr: res.data.data.nonceStr,
      package: res.data.data.package,
      signType: res.data.data.signType,
      paySign: res.data.data.paySign,
      success: function (res) {
        WxNotificationCenter.postNotificationName("RefreshMerchantBrand");
        wx.navigateBack();
      },
      fail: function (res) {

      }
    });
  }
}